$(function () {
    initIndexTime();
    /**
     * 初始首页显示的时间
     */
    function initIndexTime() {
        var time = new Date().getTime();
        setInterval(function () {
            time = time + 1000;
            var _date = new Date(time),
                yyyy = _date.getFullYear(),
                MM = (_date.getMonth() + 1) > 9 ? (_date.getMonth() + 1) : "0" + (_date.getMonth() + 1),
                dd = _date.getDate() > 9 ? _date.getDate() : "0" + _date.getDate(),
                hh = _date.getHours() > 9 ? _date.getHours() : "0" + _date.getHours(),
                mm = _date.getMinutes() > 9 ? _date.getMinutes() : "0" + _date.getMinutes(),
                ss = _date.getSeconds() > 9 ? _date.getSeconds() : "0" + _date.getSeconds();
            //星期（0-6）0星期天
            var day = _date.getDay();
            if (day == 0) {
                day = '星期日'
            } else if (day == 1) {
                day = '星期一'
            } else if (day == 2) {
                day = '星期二'
            } else if (day == 3) {
                day = '星期三'
            } else if (day == 4) {
                day = '星期四'
            } else if (day == 5) {
                day = '星期五'
            } else {
                day = '星期六'
            }
            var _hours = _date.getHours();
            if (_hours >= 3 && _hours < 6) {
                _hours = '凌晨';
            } else if (_hours >= 6 && _hours < 8) {
                _hours = '早晨';
            } else if (_hours >= 8 && _hours < 11) {
                _hours = '上午';
            } else if (_hours >= 11 && _hours < 13) {
                _hours = '中午';
            } else if (_hours >= 13 && _hours < 17) {
                _hours = '下午';
            } else if (_hours >= 17 && _hours < 19) {
                _hours = '傍晚';
            } else if (_hours >= 19 && _hours < 23) {
                _hours = '晚上';
            } else if (_hours >= 23 && _hours < 3) {
                _hours = '深夜';
            }
            $("#index-current-time").text(yyyy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss + " " + day + " " + _hours);

            if (userType == 2 && endTime != '') {
                endTime = endTime.replace(/-/g, '/');
                var _endTime = new Date(endTime);
                var _time = _endTime.getTime() - _date.getTime();
                _time = _time - 1000;
                var _d = parseInt(_time / 1000 / 60 / 60 / 24) > 9 ? parseInt(_time / 1000 / 60 / 60 / 24) : "0" + parseInt(_time / 1000 / 60 / 60 / 24);
                var _h = parseInt((_time % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60) > 9 ? parseInt((_time % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60) : "0" + parseInt((_time % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
                var _m = parseInt((_time % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60) / 1000 / 60) > 9 ? parseInt((_time % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60) / 1000 / 60) : "0" + parseInt((_time % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60) / 1000 / 60);
                var _s = parseInt(((_time % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60) % (1000 * 60)) / 1000) > 9 ? parseInt(((_time % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60) % (1000 * 60)) / 1000) : "0" + parseInt(((_time % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60) % (1000 * 60)) / 1000);
                if (_time <= 0) {
                    $("#ty-day,#ty-hours,#ty-minutes,#ty-s").text("00");
                } else {
                    $("#ty-day").text(_d);
                    $("#ty-hours").text(_h);
                    $("#ty-minutes").text(_m);
                    $("#ty-s").text(_s);
                }
            }
        }, 1000);
    }

    /**
     * 加载基本数据
     * @param callback
     */
    function baseData(callback) {
        setTimeout(function () {
            $.ajax({
                url: baseloaction +'/admin/manage/work/baseData',
                type:'post',
                dataType:'json',
                success:function (result) {
                    if(result.success==true){
                        callback(result.entity);
                    }
                }
            });
        },2000);
    }
    //显示基本数据
    baseData(function (data) {
        var userCountMap = data.userCountMap;
        $("#sumUserNum").text(userCountMap.sumUserNum);
        $("#buyUserNum").text(userCountMap.buyUserNum);
        var courseCountMap = data.courseCountMap;
        $("#sumCourseNum").text(courseCountMap.sumCourseNum);
        var examCountMap = data.examCountMap;
        $("#sumQuestionNum").text(examCountMap.sumQuestionNum);
        var orderCount = data.orderCount;
        $("#sumOrderNum").text(orderCount);
        var v96KCountMap = data.v96KCountMap;
        var use_flow = v96KCountMap.use_flow;//已使用流量
        use_flow = bToG(use_flow);//换成G
        $("#sumUsedFlow").text(parseFloat(use_flow).toFixed(2));
        var use_space = v96KCountMap.use_space;//已使用空间
        use_space = bToG(use_space);//换成G
        $("#sumUsedSpace").text(parseFloat(use_space).toFixed(2));

        //把B转换成G
        function bToG(dataNum) {
            var _dataNum = bToM(dataNum) / 1024;//换成G
            return _dataNum;
        }
        //把B转换成M
        function bToM(dataNum) {
            var _dataNum = parseInt(dataNum) /1024/1024;//换成M
            return _dataNum;
        }
        //获取待办事项的数量
        parent.getBacklogCount(function (count) {
            $("#sumBacklogNum").text(count);
            $("#backlog").click(function () {
                getRedirectMenu(baseloaction+'/admin/manage/work/myBacklog',false);
            });
        });
    });

    //执行加载工作台数据
    findUserWorkbenchData();
    /*去后台加载数据*/
    function findUserWorkbenchData() {
        var obj = {
            url: baseloaction + '/admin/manage/work/ajaxQueryWorkbench',//请求URL
            contextId: 'work-context',//响应内容页面设置内容ID
            pageCall: findUserWorkbenchData, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
            callback: function () {//数据加载完成回调
                resize();//修改样式
                $('[data-toggle="tooltip"]').tooltip();
                $("[data-toggle=popover]").popover();

                // 工作台区域排序
                var element = document.querySelector('#work-context');
                //工作三大块拖动排序
                Sortable.create(element, {
                    draggable: '.col-systemBox',
                    handle: '.ibox-move-title',
                    onUpdate: function (param) {//移动成功后的回调
                        var modList = $("#work-context>.col-systemBox");
                        var paramsList = new Array();
                        if(modList!=null && modList.length>0){
                            modList.each(function (index,mod) {
                                var em = $(mod);
                                paramsList.push({
                                    blockKey:em.data('location'),
                                    sort:index
                                });
                            });
                        }
                        var params = JSON.stringify(paramsList);
                        $.ajax({
                            url:baseloaction +'/admin/manage/work/updateModularSort',
                            type:'post',
                            data: params,
                            contentType:'application/json;charset=utf-8',
                            success:function (result) {
                                if(result.success==false){
                                    icModale(0, result.message);
                                }
                            },
                            error:function (error) {
                                icModale(0, "系统繁忙，请稍候再试");
                            }
                        });
                    }
                });
               ['provider', 'operate', 'prepare'].forEach(function (id) {
                    var _element = document.querySelector("#"+id);
                    var sortable = new Sortable(_element, {
                        draggable: '.system-item-box',
                        handle: '.ibox-icon',
                        filter: '.last-sys-item-box',
                        onMove: function (param) {
                            return !$(param.related).hasClass('last-sys-item-box');
                        },
                        onUpdate: function (param) {
                            if (param.oldIndx != param.newIndex) {
                                var _item = param.item;
                                var location = $(_item).data("location");
                                var dataList = $("#"+location+">.system-item-warp:not(.last-sys-item-box)");
                                var paramsList = new Array();
                                dataList.each(function (index,em) {
                                    paramsList.push({
                                        id:$(em).data("workbench"),
                                        sort:index
                                    });
                                });
                                var params = JSON.stringify(paramsList);
                                $.ajax({
                                    url:baseloaction +'/admin/manage/work/updateFunctionSort',
                                    type:'post',
                                    data: params,
                                    contentType:'application/json;charset=utf-8',
                                    success:function (result) {
                                        if(result.success==false){
                                            icModale(0, result.message);
                                        }else{
                                            resize();//修改样式
                                        }
                                    },
                                    error:function (error) {
                                        icModale(0, "系统繁忙，请稍候再试");
                                    }
                                })
                            }
                        }
                    });
               });
            }
        };
        ajaxGetListData(obj)
    }

    // 权限图标样式
    function resize() {
        $('#work-context div.ibox-content div.row').each(function () {
            var elements = $(this).find('div.system-item-warp');
            var single_width = elements.eq(0).css('width');
            var width = $(this).css('width');
            single_width = parseFloat(single_width.replace('px', ''));
            width = parseFloat(width.replace('px', ''));
            var length = Math.floor(width / single_width);
            elements.each(function (i, v) {
                i = i % length;
                $(v).find('div.ibox-title > span.ibox-icon').attr('class', 'ibox-icon text-center pull-left m-r-sm move');
                if (i != 0 && (i = i % length) != 0) {
                    $(v).find('div.ibox-title > span.ibox-icon').addClass('ibox-icon' + (i + 1));
                }
            });
        });
    }
    $('body').on('click', '#work-context div.last-sys-item-box', function () {//点击添加权限
        var type = $(this).data("location");
        var context = '';
        $.ajax({
            url: baseloaction +'/admin/manage/work/initAddNotFunctionList',
            type: 'post',
            dataType: 'text',
            data: {'type': type},
            async: false,
            success: function (result) {
                context = result;
            },
            error: function () {
                icModale(0, '系统错误，权限数据加载失败');
            }
        });
        var length = $(context).find('.sys-item-ele').length;
        if (length <= 0) {
            icModale(0, '已没有可以添加的权限了');
            return;
        }
        parent.layer.open({
            type: 1,
            area: ['1020px', '500px'],
            skin: 'layui-layer-demo',
            title: '提示-最多可添加 ' + length + ' 个系统',
            content: context,
            btn: ['确认添加', '取消'],
            yes: function (index, layero) {
                var selected = layero.find('input[name="functionId"]:checked');
                var unSelected = layero.find('input[name="functionId"]').not(":checked");
                if (selected.length == 0) {
                    icModale(0, '请选择要添加的权限');
                } else {
                    var functionIds = selected.map(function () {
                        return this.value
                    }).get().join(',');
                    var unSelectedIds = unSelected.map(function () {
                        return this.value
                    }).get().join(',');
                    addUserWorkFunction(functionIds,unSelectedIds);
                    parent.layer.close(index);
                }

            },
            success: function (layero) {
                var width = $('div.system-item-box').eq(0).css('width').replace('px', '');
                var length = Math.floor(1020 / width);
                layero.find('div.system-item-box').each(function (i, v) {
                    i = i % length;
                    $(v).find('div.ibox-title > span.ibox-icon').attr('class', 'ibox-icon text-center pull-left m-r-sm');
                    if (i != 0 && (i = i % length) != 0) {
                        $(v).find('div.ibox-title > span.ibox-icon').addClass('ibox-icon' + (i + 1));
                    }
                });
            }
        });
    }).on('click', "#work-context .sys-function-box-r", function (e) {// 权限路径跳转
        var url = $(this).data('uri');
        if (url) {
            getRedirectMenu(url, false);
        } else {
            var id = $(this).data('id');
            var menu = window.parent.document.getElementById('side-menu');
            var target = $(menu).find('a[data-id="' + id + '"]')[0];
            window.parent.initM($(target).parent());
        }
    });

    /**
     * 添加权限显示
     * @param functionIds 权限ID串
     */
    function addUserWorkFunction(functionIds,unSelectedIds) {
        $.ajax({
            type:'post',
            url:baseloaction +'/admin/manage/work/addUserWorkFunction',
            data:{'functionIds':functionIds,'unSelectedIds':unSelectedIds},
            async: false,
            success:function(result){
                if(result.success==false){
                    icModale(0, result.message);
                }else{
                    //添加成功重新加载工作的权限数据
                    findUserWorkbenchData();
                }
            },
            error:function(error){
                icModale(0, '系统错误，权限添加失败');
            }
        });
    }

});


